package controller

import (
	"ruanGongKeShe16Zu/common/utils"
	"ruanGongKeShe16Zu/response"
	"ruanGongKeShe16Zu/service"
	"ruanGongKeShe16Zu/service/vo"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ICategoryController interface {
	GeneralController
	ListCategory(ctx *gin.Context)
}

type CategoryController struct {
	Service service.CategoryService
}

func NewCategoryController() ICategoryController {
	service := service.GetCategoryService()
	return CategoryController{
		Service: *service,
	}
}

func (c CategoryController) Create(ctx *gin.Context) {
	var req vo.CategoryReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.Fail(ctx, nil, "分类名称不能为空!")
		return
	}
	resp, err := c.Service.Create(ctx, &req)
	if err != nil {
		utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "创建失败")
		return
	}
	response.Success(ctx, gin.H{"category": resp}, "创建成功")
}

func (c CategoryController) Retrieve(ctx *gin.Context) {
	//获取path中的参数
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	category, err := c.Service.Retrieve(ctx, categoryId)
	if err != nil {
		response.Fail(ctx, nil, "分类不存在")
		return
	}
	response.Success(ctx, gin.H{"category": category}, "查询成功")
}

func (c CategoryController) Update(ctx *gin.Context) {
	//绑定body中的参数
	var requestCategory vo.CategoryReq
	if err := ctx.ShouldBind(&requestCategory); err != nil {
		response.Fail(ctx, nil, "分类名称不能为空!")
		return
	}
	//获取path中的参数
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	updateCategory, err := c.Service.Retrieve(ctx, categoryId)
	if err != nil {
		response.Fail(ctx, nil, "分类不存在")
		return
	}

	//更新分类
	//可传map,struct,name value
	category, err := c.Service.Update(ctx, updateCategory, requestCategory.Name)
	if err != nil {
		response.Fail(ctx, nil, "更新失败")
		return
	}
	response.Success(ctx, gin.H{"category": category}, "更新成功")
}

func (c CategoryController) Delete(ctx *gin.Context) {
	//获取path中的参数
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	_, err := c.Service.Retrieve(ctx, categoryId)
	if err != nil {
		response.Fail(ctx, nil, "分类不存在")
		return
	}

	err = c.Service.Delete(ctx, categoryId)
	if err != nil {
		response.Fail(ctx, nil, "删除失败，请重试")
		return
	}

	response.Success(ctx, nil, "删除成功")
}

func (c CategoryController) ListCategory(ctx *gin.Context) {
	var req vo.ListCategoryReq
	if err := ctx.ShouldBind(&req); err != nil {
		// 参数校验
		utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "参数不能为空!")
		return
	}

	resp, err := c.Service.CategoryList(ctx, &req)
	if err != nil {
		utils.LogrusObj.Infoln(err)
		response.Fail(ctx, nil, "查询失败")
		return
	}
	response.Success(ctx, gin.H{"categories": resp}, "查询成功")
}
